<template>
<div class="xy-region-input">
  <el-select :disabled="disabled" placeholder="省" v-model="regionObj.province" @change="$emit('province')">
    <el-option label="请选择" value="0"></el-option>
        <el-option
          v-for="province of provinces"
          :key="province.region_id"
          :label="province.region_name"
          :value="province.region_id">
        </el-option>
      </el-select>
      <el-select :disabled="disabled" placeholder="市" v-model="regionObj.city" @change="$emit('city')">
        <el-option label="请选择" value="0"></el-option>
        <el-option
          v-for="city of citys"
          :key="city.region_id"
          :label="city.region_name"
          :value="city.region_id">
        </el-option>
      </el-select>
      <el-select :disabled="disabled" placeholder="区" v-model="regionObj.area" @change="$emit('area')">
        <el-option label="请选择" value="0"></el-option>
        <el-option
          v-for="area of areas"
          :key="area.region_id"
          :label="area.region_name"
          :value="area.region_id">
        </el-option>
      </el-select>
</div>
</template>

<script>
import regionModel from '@M/region'
export default {
  name:"Region",
  props:{
    value:{
      type:Object,
      default:() => {
        return {
          province:"",
          city:"",
          area:""
        }
      }
    },
    disabled:{
      type:Boolean,
      default:false
    }
  },
  data(){
    return {
      regionObj:{
        province:"",
        city:"",
        area:""
      },
      provinces:[],
      citys:[],
      areas:[]
    }
  },
  mounted() {
    this.regionObj = this.value;
    this.provinces = regionModel.getProvince();
  },
  watch:{
    value:{
      handler(){
        this.regionObj = this.value;
      },
      deep:true
    },

   "regionObj.province":function(){
     if(!this.regionObj.province){
       this.regionObj.city = "0";
       this.citys = [];
       return;
     }
     this.citys = regionModel.getCity(this.regionObj.province);
     var exists = false;
     this.citys.some(item => {
       if(item.region_id == this.regionObj.city){
          exists = true;
          return exists;
       }
     });
     if(!exists){
       this.regionObj.city = "0";
     }
   } ,
   "regionObj.city":function(){
     if(!this.regionObj.city){
       this.regionObj.area = "0";
       this.areas = [];
       return;
     }
     this.areas = regionModel.getArea(this.regionObj.city);
     var exists = false;
     this.areas.forEach(item => {
       if(item.region_id == this.regionObj.area){
         exists = true;
       }
     });
     if(!exists){
       this.regionObj.area = "0";
     }
   } ,
   "regionObj.area":function(){
     
   } 
  }
}
</script>

<style lang="scss">
  .xy-region-input{
    display: inline-block;
    width: 100%;
  }
</style>

